import router from '../router'
import axios from 'axios'

import {
    Message,
} from 'element-ui'
 let baseURL = "http://127.0.0.1:3000"

const service = axios.create({
    baseURL,
    // baseURL: "http://apis.taizzpx.com",
    timeout: 10000,
})

service.defaults.withCredentials = true; //配置为true 允许携带信息头

// service.defaults.headers = {
//         'Authorization': 'Basic cGxhdGZvcm1fbGljZW5zZV9hZG1pbjpod192ZGlfbGljZW5zZQ=='
//     }
//请求发出前拦截
service.interceptors.request.use(function(config) {
    let token = localStorage.getItem('token')
    if (token && config.url !== "/login") {
        config.headers.Authorization = 'Basic' + ' ' + token;

    } else {
        delete config.headers.Authorization
            // config.headers.Authorization = ""
    }
    return config;
}, function(error) {
    return Promise.reject(error)
})

/* 响应拦截器 */
service.interceptors.response.use(function(response) {
    // console.log('响应拦截器', response.data)
    if (response.data.code === 200) {
        return response.data;
    } else if (response.data.code === 10086) {
        Message({
            message: `${response.data.message}  请重新登录`,
            type: 'error',
            duration: 2000
        })
        router.replace({
            path: '/login' // 到登录页重新获取token
        })
        localStorage.removeItem("token")

    } else {



        Message({
            message: `${response.data.message} `,
            type: 'error',
            duration: 2000
        })
    }

    return response.data;
}, function(error) {

    // return Promise.reject(error)
    let originalRequest = error.config
    if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1 && !originalRequest._retry) {
        // eslint-disable-next-line
        Message({
            message: `请检查网络再重新连接`,
            type: 'warning',
            duration: 3000
        })
        return Promise.reject('请检查网络再重新连接')
    }
    return Promise.reject(error)

})


// post
export function postAction(url, parameter) {
    return service({
        url: url,
        method: 'post',
        data: parameter
    })
}

// get
export function getAction(url, parameter) {
    return service({
        url: url,
        method: 'get',
        params: parameter,
    })
}


// deleteAction
export function deleteAction(url, parameter) {
    return service({
        url: url,
        method: 'delete',
        params: parameter,

    })
}
// put
export function putAction(url, parameter) {
    return service({
        url: url,
        method: 'put',
        params: parameter
    })
}
//上传文件
export function postUpload(url, parameter, config) {


    return service({
        url: url,
        method: 'post',
        data: parameter,
        // ContentType: 'multipart/form-data',
        headers: config,
        // Authorization: localStorage.getItem("token")
    })
}
export function baseURL() {
    return baseURL
}